/*
 * @Author: ke.xue
 * @Date: 2022-04-20 22:04:25
 * @LastEditors: ke.xue
 * @LastEditTime: 2022-04-20 22:51:15
 * @FilePath: \product-display\src\utils\aMap.js
 * @Description: 地图调用
 */
import store from '../store'
const url = 'https://api.map.baidu.com/api?v=1.0&type=webgl&ak=IeKN6jdrUiIC1zhBt74dZS4MFAeVoDL4&callback=initialize'
const jsapi = document.createElement('script')
jsapi.charset = 'utf-8'
jsapi.src = url
jsapi.onload = initialize
document.head.appendChild(jsapi)
let BMapGL = window.BMapGL

function initialize () {
  console.log(window.BMapGL, 'window.BMapGL')
  BMapGL = window.BMapGL
  const timer = setTimeout(() => {
    store.commit('setMapInit', true)
    clearTimeout(timer)
  }, 1500)
}

class AMap {
  constructor () {
    this.mapSelectionPoint = null // 地图选点控件
    this.marker = null // 默认标注
    this.label = null // 文本标注
    this.markPoint = null // 点
    this.polyline = null // 线
    this.geocoder = null // 正逆地理坐标
    this.infoWindow = null // 地图
  }

  // 初始化地图
  initView (id, options) {
    const { addLocationControl, enableScrollWheelZoom, addMapSelectionPoint, mapSelectionPointCallback } = options
    this.infoWindow = new BMapGL.Map(id) // 创建Map实例
    this.setMapCenter(options)
    this.infoWindow.enableScrollWheelZoom(enableScrollWheelZoom || true) // 开启鼠标滚轮缩放
    addLocationControl && this.addLocationControl()
    addMapSelectionPoint && this.addMapSelectionPoint(mapSelectionPointCallback, false)
  }

  // 添加默认标记
  addDefaultMarker (options) {
    const { latitude, longitude } = options
    this.marker = new BMapGL.Marker(new BMapGL.Point(longitude, latitude)) // 创建标注
    this.infoWindow.addOverlay(this.marker) // 将标注添加到地图中
  }

  // 添加文本标注
  addLabel (options, content) {
    const { latitude, longitude } = options
    this.label = new BMapGL.Label(content, { // 创建文本标注
      position: new BMapGL.Point(longitude, latitude), // 设置标注的地理位置
      offset: new BMapGL.Size(-10, -50) // 设置标注的偏移量
    })
    this.label.setStyle({ // 设置label的样式
      color: '#000',
      fontSize: '14px',
      border: '1px solid red',
      borderRadius: '2px',
      lineHeight: '20px',
      padding: '0 10px'
    })
    this.infoWindow.addOverlay(this.label) // 将标注添加到地图中
  }

  // 坐标=>地址
  getAddress (options) {
    const { latitude, longitude } = options
    if (!this.geocoder) {
      this.geocoder = new BMapGL.Geocoder()
    }
    return new Promise((resolve, reject) => {
      this.geocoder.getLocation(new BMapGL.Point(longitude, latitude), function (result) {
        if (result) {
          resolve(result)
        } else {
          reject(new Error(result))
        }
      })
    })
  }

  // 地址=>坐标
  getCoordinate (address, cityName) {
    if (!this.geocoder) {
      this.geocoder = new BMapGL.Geocoder()
    }
    return new Promise((resolve, reject) => {
      this.geocoder.getPoint(address, function (point) {
        console.log(point)
        if (point) {
          resolve(point)
        } else {
          reject(new Error(point))
        }
      }, cityName)
    })
  }

  // 清除覆盖物
  clearView () {
    if (this.infoWindow) {
      this.infoWindow.clearOverlays()
    }
  }

  // 添加定位控件
  addLocationControl () {
    const locationControl = new BMapGL.LocationControl({
      // 控件的停靠位置
      anchor: 'BMAP_ANCHOR_BOTTOM_RIGHT',
      // 控件基于停靠位置的偏移量（可选）
      offset: new BMapGL.Size(20, 20)
    })
    locationControl.addEventListener('locationSuccess', function (e) {
      console.log(e, 'locationSuccess')
    })
    locationControl.addEventListener('locationError', function (e) {
      console.log(e, 'locationError')
    })
    // 将控件添加到地图上
    this.infoWindow.addControl(locationControl)
  }

  // 地图选点控件
  addMapSelectionPoint (callback, status) {
    const _this = this
    if (this.mapSelectionPoint) {
      this.infoWindow.removeControl(this.mapSelectionPoint)
    }
    function ZoomControl () {
      this.defaultAnchor = 'BMAP_ANCHOR_TOP_RIGHT'
      this.defaultOffset = new BMapGL.Size(20, 20)
    }
    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMapGL.Control()

    // 自定义控件必须实现自己的initialize方法，并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    if (status) {
      ZoomControl.prototype.initialize = function (map) {
        // 创建一个dom元素
        var div = document.createElement('div')
        // 添加文字说明
        div.appendChild(document.createTextNode('关闭地图选点'))
        // 设置样式
        div.style.cursor = 'pointer'
        div.style.padding = '7px 10px'
        div.style.boxShadow = '0 2px 6px 0 rgba(27, 142, 236, 0.5)'
        div.style.borderRadius = '5px'
        div.style.backgroundColor = 'white'
        // 绑定事件,点击一次放大两级
        div.onclick = function () {
          map.removeEventListener('click')
          _this.addMapSelectionPoint(callback, false)
        }
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div)
        // 将DOM元素返回
        return div
      }
    } else {
      ZoomControl.prototype.initialize = function (map) {
        // 创建一个dom元素
        var div = document.createElement('div')
        // 添加文字说明
        div.appendChild(document.createTextNode('地图选点'))
        // 设置样式
        div.style.cursor = 'pointer'
        div.style.padding = '7px 10px'
        div.style.boxShadow = '0 2px 6px 0 rgba(27, 142, 236, 0.5)'
        div.style.borderRadius = '5px'
        div.style.backgroundColor = 'white'
        // 绑定事件,点击一次放大两级
        div.onclick = function () {
          map.addEventListener('click', function (e) {
            callback && callback(e)
          })
          _this.addMapSelectionPoint(callback, true)
        }
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div)
        // 将DOM元素返回
        return div
      }
    }

    // 创建控件元素
    this.mapSelectionPoint = new ZoomControl()
    // 添加到地图中
    this.infoWindow.addControl(this.mapSelectionPoint)
  }

  // 写入地图中心点
  setMapCenter (options) {
    const { latitude, longitude, zoom } = options
    this.infoWindow.centerAndZoom(new BMapGL.Point(longitude, latitude), zoom || 16) // 初始化地图,设置中心点坐标和地图级别
  }
}

export default new AMap()
